package com.thti.mecool.client.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.threeti.mecool.mobile.interfaces.dto.ProjectStoreWithSellIntoDto;
import com.threeti.mecool.mobile.interfaces.dto.SalesPromoterDto;
import com.threeti.mecool.mobile.interfaces.dto.SellIntoDto;
import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.command.send.saleinto.SellIntoSend;
import com.thti.mecool.client.util.Util;
import com.thti.mecool.client.widget.AdapterForLinearLayout;
import com.thti.mecool.client.widget.AlterDialogWidget;
import com.thti.mecool.client.widget.LinearLayoutForListView;
import com.thti.mecool.client.widget.Toolbar;


public class SellDetailActivity extends BaseActivity {
	TextView sellStateTextView,situationTextView,stateTextView,dateTextView,typesTextview;
	LinearLayout sellStateLinearLayout,situationLinearLayout,stateLinearLayout,addSalersLinearLayout,typesLinearLayout;
	LinearLayoutForListView listView=null;
	ExpandableListView salersListView;
	ImageButton addSalersButton;
	List<SalesPromoterDto> salesPromoters;
	List<HashMap<String, Object>> list;
	SellIntoDto sellinto;
	int item;
	AdapterForLinearLayout Layoutadpater; 
	String[] SalesState={"卖进中","卖进成功","无法卖进","取消","未上报"};
	String[] Situations={"无","其它","形象堆","联合堆"};
	String[] ExecuteStates={"执行中","下周可执行","执行过现在停止","从未执行"};
	String[] Types={"无","门店问题","堆头问题","其他"};
	int[] ViewIds = new int[] { R.id.mecool_sell_detail_item_sellstate,
			R.id.mecool_sell_detail_item_situation,
			R.id.mecool_sell_detail_item_state,
			R.id.mecool_sell_detail_item_type};
	ArrayList<EditText> views;
	Button save;
	EditText describeEdiText,memoEditText;
	ProjectStoreWithSellIntoDto ssd;
	Date curDate;
	int i=1;
	public static Handler handler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		noTitle();
		setContentView(R.layout.mecool_sell_detail);
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		init();
		initToolbar();
		initData();
		handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				if(msg.what==0xAA){
					Util.sendToast(SellDetailActivity.this, "保存成功");
					finish();
				}
				super.handleMessage(msg);
			}	
		};
		service();
	}
	
	public void initToolbar(){
		Toolbar toolbar=new Toolbar(this);
		toolbar.setToolbarCentreText("卖进详细");
		Toolbar.left_btn.setOnClickListener(leftbuttonListener);
		Toolbar.hideRightButton();
		Toolbar.left_btn.setImageResource(R.drawable.mecool_go_back);
	}
	private OnClickListener leftbuttonListener=new ImageButton.OnClickListener(){

		@Override
		public void onClick(View v) {
			finish();
		}};
	private void init(){
		sellStateTextView=(TextView)findViewById(R.id.mecool_sell_detail_item_sellstate);
		situationTextView=(TextView)findViewById(R.id.mecool_sell_detail_item_situation);
		stateTextView=(TextView)findViewById(R.id.mecool_sell_detail_item_state);
		typesTextview=(TextView)findViewById(R.id.mecool_sell_detail_item_type);
		describeEdiText=(EditText)findViewById(R.id.mecool_sell_detail_item_describe);
		memoEditText=(EditText)findViewById(R.id.mecool_sell_detail_item_memo);
		sellStateLinearLayout=(LinearLayout)findViewById(R.id.mecool_sell_detail_sellstate_linearlayout);
		situationLinearLayout=(LinearLayout)findViewById(R.id.mecool_sell_detail_situation_linearlayout);
		stateLinearLayout=(LinearLayout)findViewById(R.id.mecool_sell_detail_state_linearlayout);
		typesLinearLayout=(LinearLayout)findViewById(R.id.mecool_sell_detail_item_type_layout);
		dateTextView=(TextView)findViewById(R.id.mecool_sell_detail_item_date);
		save=(Button)findViewById(R.id.mecool_sell_detail_item_save);
		addSalersButton=(ImageButton)findViewById(R.id.mecool_sell_detail_add_salers);
		listView=(LinearLayoutForListView)findViewById(R.id.mecool_sell_detail_salers_listview);
		addSalersLinearLayout=(LinearLayout)findViewById(R.id.mecool_sell_detail_addsales_linearlayout);
		sellinto=new SellIntoDto();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date curDate = new Date(System.currentTimeMillis());	
		dateTextView.setText(sdf.format(curDate));
	}

	private void initData() {
		ssd = (ProjectStoreWithSellIntoDto) getIntent()
				.getSerializableExtra("SSD");
		sellStateTextView.setText(SalesState[ssd.getSellInto().getStatus()]);
//		date.setText(ssd.getSellInto().getLastModified());
		situationTextView.setText(Situations[ssd.getSellInto().getTgStockBaseDesc()]);
		stateTextView.setText(ExecuteStates[ssd.getSellInto().getExecutionStatus()]);
//		views.get(3).setText(ssd.getSellInto().getProblemType());
		describeEdiText.setText(ssd.getSellInto().getProblemDescription());
		memoEditText.setText(ssd.getSellInto().getDescription());
		salesPromoters=ssd.getSellInto().getSalesPromoters();
		sellinto=ssd.getSellInto();
	}	
	OnClickListener clickListener=new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch(v.getId()){
			case R.id.mecool_sell_detail_addsales_linearlayout:
				if(i%2==0){
					listView.setVisibility(View.GONE);
				}else{
					listView.setVisibility(View.VISIBLE);
				}
				i++;
				break;
			case R.id.mecool_sell_detail_item_date:
				final SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy" + "MM" + "dd");
				final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy" + "年" + "MM" + "月"
						+ "dd" + "日");
				curDate=new Date(System.currentTimeMillis());
				new DatePickerDialog(SellDetailActivity.this, new OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						try {
							if(Integer.valueOf(
									sdf3.format(sdf2.parse(year+"年"+(monthOfYear+1)+"月"+dayOfMonth+"日")))
									.intValue() >= Integer.valueOf(
									sdf3.format(curDate)).intValue()){
								dateTextView.setText(year+"年"+(monthOfYear+1)+"月"+dayOfMonth+"日");
							}else{
								Util.sendToast(SellDetailActivity.this, "不能选已过时间");
							}
						} catch (NumberFormatException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					};
				}, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
				break;
			case R.id.mecool_sell_detail_sellstate_linearlayout:
				AlterDialogWidget salesStateDialog=new AlterDialogWidget(SellDetailActivity.this);
				salesStateDialog.setTitle("选择卖进情况");
				salesStateDialog.setItems(SalesState);
				salesStateDialog.setReturnView(sellStateTextView);
				salesStateDialog.show();
				break;
			case R.id.mecool_sell_detail_situation_linearlayout:
				AlterDialogWidget situationsDialog=new AlterDialogWidget(SellDetailActivity.this);
				situationsDialog.setTitle("选择堆头情况");
				situationsDialog.setItems(Situations);
				situationsDialog.setReturnView(situationTextView);
				situationsDialog.show();
				break;
			case R.id.mecool_sell_detail_state_linearlayout:
				AlterDialogWidget executeStatesDialog=new AlterDialogWidget(SellDetailActivity.this);
				executeStatesDialog.setTitle("选择 执行情况");
				executeStatesDialog.setItems(getSring(sellStateTextView.getText().toString()));
				executeStatesDialog.setReturnView(stateTextView);
				executeStatesDialog.show();
				break;
			case R.id.mecool_sell_detail_item_type_layout:
				AlterDialogWidget typesStatesDialog=new AlterDialogWidget(SellDetailActivity.this);
				typesStatesDialog.setTitle("选择问题类型");
				typesStatesDialog.setItems(Types);
				typesStatesDialog.setReturnView(typesTextview);
				typesStatesDialog.show();
				break;
			case R.id.mecool_sell_detail_add_salers:
				Intent intent=new Intent(SellDetailActivity.this,AddSalersActivity.class);
				startActivityForResult(intent,10);
				break;
			case R.id.mecool_sell_detail_item_save:
				sellinto.setProjStoreId(ssd.getId());
				sellinto.setUserId(String.valueOf(getCurrentUser().getId()));
				sellinto.setStatus(getArrayNum(sellStateTextView.getText().toString(),SalesState));
				sellinto.setTgStockBaseDesc(getArrayNum(situationTextView.getText().toString(),Situations));
				sellinto.setExecutionStatus(getArrayNum(stateTextView.getText().toString(),ExecuteStates));
				sellinto.setProblemType(getArrayNum(typesTextview.getText().toString(),Types));
				sellinto.setProblemDescription(describeEdiText.getText().toString());
				sellinto.setDescription(memoEditText.getText().toString());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy" + "/" + "MM" + "/" + "dd"
						 + " HH:mm");
				curDate = new Date(System.currentTimeMillis());
				System.out.println(sdf.format(curDate));
				sellinto.setLastModified(sdf.format(curDate));
				sellinto.setSalesPromoters(salesPromoters);
				SellIntoSend.editSellInto(sellinto);
				break;
			}
		}
	};
	
	
	private void service(){
		sellStateLinearLayout.setOnClickListener(clickListener);
		situationLinearLayout.setOnClickListener(clickListener);
		stateLinearLayout.setOnClickListener(clickListener);
		typesLinearLayout.setOnClickListener(clickListener);
		addSalersLinearLayout.setOnClickListener(clickListener);
		addSalersButton.setOnClickListener(clickListener);
		save.setOnClickListener(clickListener);
		list=new ArrayList<HashMap<String,Object>>();
        list=getListData(salesPromoters);
        Layoutadpater = new AdapterForLinearLayout(
                this, list, R.layout.mecool_sale_detail_listview_item_layout, 
                new String[] {"key_name","value_name"}, 
                new int[] { R.id.mecool_sale_detail_listview_item_layout_name,R.id.mecool_sale_detail_listview_item_layout_value});
//      事件操作，并通过下标得到数据源：
        listView.setOnclickLinstener(onClickListener);
        listView.setOnLongClickListener(longClickListener);     
        listView.setAdapter(Layoutadpater);
	}

	
	OnClickListener onClickListener=new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
//        	String toShow = Layoutadpater.get(Integer.parseInt(v.getTag().toString()), "key_name");
//        	String toshow2 = Layoutadpater.get(Integer.parseInt(v.getTag().toString()), "value_name");
//            Toast.makeText(
//            		SellDetailActivity.this,
//            		toShow + "---" + toshow2, 1000).show();
            Intent intent=new Intent(SellDetailActivity.this,AddSalersActivity.class);
            intent.putExtra("salers", salesPromoters.get(Integer.parseInt(v.getTag().toString())));
            intent.putExtra("whichsaler", Integer.parseInt(v.getTag().toString()));
            intent.putExtra("ismodify", true);
            startActivityForResult(intent, 11);
		}
	};
	
	OnLongClickListener longClickListener=new OnLongClickListener() {
		
		@Override
		public boolean onLongClick(View v) {
			// TODO Auto-generated method stub
			System.out.println("Integer.parseInt(v.getTag().toString())"+Integer.parseInt(v.getTag().toString()));
			item=Integer.parseInt(v.getTag().toString());
			new AlertDialog.Builder(SellDetailActivity.this).setTitle("确认要删除吗?").setPositiveButton("确认", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					list.remove(item);
					salesPromoters.remove(item);
		            Layoutadpater.notifyDataSetChanged();
		            listView.setAdapter(Layoutadpater);
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			}).create().show();
			return false;
		}
	};
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==10){
			if(resultCode==RESULT_OK){
				if(data.getBooleanExtra("issave", false)){
					String name=data.getStringExtra("name");
		            HashMap<String, Object> map = new HashMap<String, Object>();
		            map.put("key_name", name);
		            map.put("value_name","");
		            list.add(map);
		            Layoutadpater.notifyDataSetChanged();
		            listView.setAdapter(Layoutadpater);
					String tel=data.getStringExtra("tel");
					String id=data.getStringExtra("id");
					String onDutyTime=data.getStringExtra("starttime");
					String offTime=data.getStringExtra("endtime");
					SalesPromoterDto salesPromoterDto=new SalesPromoterDto();
					salesPromoterDto.setIdCardNo(id);
					salesPromoterDto.setName(name);
					salesPromoterDto.setOnDutyTime(onDutyTime);
					salesPromoterDto.setOffTime(offTime);
					salesPromoterDto.setPhone(tel);
					salesPromoters.add(salesPromoterDto);
				}
			}
		}else if(requestCode==11){
			if(resultCode==RESULT_OK){
				int modifyItem=data.getIntExtra("salersitem", -1);
				String name=data.getStringExtra("name");
				list.get(modifyItem).put("key_name", name);
	            Layoutadpater.notifyDataSetChanged();
	            listView.setAdapter(Layoutadpater);
	            String tel=data.getStringExtra("tel");
				String id=data.getStringExtra("id");
				String onDutyTime=data.getStringExtra("starttime");
				String offTime=data.getStringExtra("endtime");
				salesPromoters.get(modifyItem).setName(name);
				salesPromoters.get(modifyItem).setPhone(tel);
				salesPromoters.get(modifyItem).setIdCardNo(id);
				salesPromoters.get(modifyItem).setOnDutyTime(onDutyTime);
				salesPromoters.get(modifyItem).setOffTime(offTime);
			}
		}
	}
	
	public List<HashMap<String, Object>> getListData(List<SalesPromoterDto> listSales){
		List<HashMap<String, Object>> list=new ArrayList<HashMap<String,Object>>();
		for (int i = 0; i < listSales.size(); i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("key_name", listSales.get(i).getName());
            map.put("value_name","");
            list.add( map );
        }
		return list;
	}
	public  String[] getSring(String str){
		int j=0;
		for (int i = 0; i < SalesState.length; i++) {
			System.out.println("23124");
			if(str.equals(SalesState[i])){
				j=i;
				break;
			}
		}
		if(j==0){
			return new String[]{"下周可执行","执行过现在停止","从未执行"};
		}else if(j==1){
			return ExecuteStates;
		}else{
			return new String[]{"从未执行"};
		}
		
	}
	private int getArrayNum(String value,String[] array){
		int item=0;
		for(int i=0;i<array.length;i++){
			if(value.equals(array[i])){
				item=i;
			}
		}
		return item;
	}
	
	
}
